In [1]:
# create an empty dictionary
empty_dict = {}
empty_dict = dict()
# create a dictionary with content
family = {'dad':'homer', 'mom':'marge', 'size':6}
faimly = dict(dad='homer', mom='marge', size=6)
family
Out[1]:
In [1]:
# convert a liist of tuples into a dictionary
list_of_tuples = [('dad','homer'), ('mom','marge'), ('size',6)]
family=dict(list_of_tuples)
family
Out[1]:
In [3]:
# creating a dictionary from a sequence of keys (no values created)
seq = ('name', 'age', 'sex')
d = dict.fromkeys(seq)
d
Out[3]:
In [7]:
# creating a dictionary from a sequence of keys and a value to use as the default value
d = dict.fromkeys(seq, 10)
d
Out[7]:
In [3]:
# pass a key ti return its value
family['dad']
Out[3]:
In [4]:
# return number of key-value pairs
len(family)
Out[4]:
In [5]:
# check if key exists in dictionary
'mom' in family
Out[5]:
In [6]:
# only keys, not values, are checked
'marge' in family
Out[6]:
In [7]:
# returns an iterable view of keys
family.keys()
Out[7]:
In [8]:
# returns an iterable view of values
family.values()
Out[8]:
In [16]:
# returns an iterable view of key-value pairs
family.items()
Out[16]:
In [17]:
# equivalent to a dictionary lookup
family.get('mom')
Out[17]:
In [18]:
# this would throw an error since the key does not exist
# family['grandma']
In [20]:
# return None if not found
family.get('grandma')
In [22]:
# provide a default return value if not found
family.get('grandma', 'not found')
Out[22]:
In [23]:
# accesss an element within a list inside a dictionary
family['kids'][0]
Out[23]:
In [11]:
# edit an existing entry
family['cat'] = 'snowball'
family
Out[11]:
In [12]:
# edit an existing entry
family['cat'] = 'snowball ii'
family
Out[12]:
In [13]:
# delete an entry
del family['cat']
family
Out[13]:
In [14]:
# dictionary value can be a list
family['kids']=['bart','lisa']
family
Out[14]:
In [15]:
# remove an entry and return the value
family.pop('dad')
Out[15]:
In [24]:
# add multiple-entries
family.update({'baby':'maggie', 'mom':'Marge', 'grandpa':'abe'})
family
Out[24]:
In [25]:
family['kids'].remove('lisa')
family
Out[25]:
In [28]:
# replaces %(baby)s with the result of looking up 'baby' in family
'youngest child is %(baby)s' % family
Out[28]:
Ways to get a default element add to the dictionary on first access
In [29]:
# using defaultdict
from collections import defaultdict
d=defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(3)
d
Out[29]:
In [1]:
# using setdefault
d={}
d.setdefault('a',[]).append(1)
d.setdefault('a',[]).append(2)
d.setdefault('b',[]).append(3)
d
Out[1]:
In [2]:
a = {
'x' : 1,
'y' : 2,
'z' : 3
}
b = {
'w' : 10,
'x' : 11,
'y' : 2
}
# Find keys in common
a.keys() & b.keys() # { 'x', 'y' }
Out[2]:
In [3]:
# Find keys in a that are not in b
a.keys() - b.keys() # { 'z' }
Out[3]:
In [4]:
# Find (key,value) pairs in common
a.items() & b.items() # { ('y', 2) }
Out[4]:
These kinds of operations can also be used to alter or filter dictionary contents. For example, suppose you want to make a new dictionary with selected keys removed. Here is some sample code using a dictionary comprehension:
In [5]:
{key:a[key] for key in a.keys() - {'z', 'w'}}
Out[5]:
In [1]:
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
# Make a dictionary of all prices over 200
{ key:value for key, value in prices.items() if value > 200 }
Out[1]:
In [2]:
# Make a dictionary of tech stocks
tech_names = { 'AAPL', 'IBM', 'HPQ', 'MSFT' }
{ key:value for key,value in prices.items() if key in tech_names }
Out[2]: